//
//  GetUserModel.swift
//  AliBaiChuan
//
//  Created by 郑东喜 on 2017/2/8.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  用户信息模型

import UIKit

class GetUserModel: NSObject {
    
    static let shared = GetUserModel()
    
    ///用户名
    lazy var userNickName : String = ""
    
    ///openID
    lazy var userOpenID : String = ""
    
    ///openSID
    lazy var userSID : String = ""
    
    ///头像地址
    lazy var avatra : String = ""
    
    
    ///用户信息
    var userDataDic : NSMutableArray = NSMutableArray()
    
    let login : ALBBSDK = ALBBSDK()
    
    let nav = UIApplication.shared.keyWindow?.rootViewController
    

    ///闭包传值
    //外部闭包变量
    var comfun:((_ _nickName:String,_ _openID : String,_ _opnSID : String,_ _headURL : String,_ _dataArray :NSMutableArray )->Void)?
 
    /// 获取的用户信息
    ///
    /// - Parameter comfun: _
    func getUData(comfun:((_ _nickName:String,_ _openID : String,_ _opnSID : String,   _ _headURL : String,_ _dataArray :NSMutableArray)->Void)?) -> Void {
        self.comfun = comfun
        
        let login : ALBBSDK = ALBBSDK()
        
        ///设置参数，打开方式
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
//        showParams.openType = .auto
        showParams.openType = .native
        
        login.auth(showParams.isNeedPush ? nav?.navigationController! : nav, successCallback: { (result) in
            ///nickName
            let _nickName = result?.getUser().nick
            
            ///openID
            let _openID = result?.getUser().openId
            
            ///openSID
            let _openSID = result?.getUser().openSid
            
            ///avatrrURL
            let _headURL = result?.getUser().avatarUrl
            
            self.userNickName = _nickName!
            self.userOpenID = _openID!
            self.userSID = _openSID!
            self.avatra = _headURL!
            
            
            if self.userDataDic.count != 0 {
                self.userDataDic.removeAllObjects()
            } else {
                ///添加到用户信息
                self.userDataDic.add(_nickName as Any)
                self.userDataDic.add(_openID as Any)
                self.userDataDic.add(_openSID as Any)
                self.userDataDic.add(_headURL as Any)
                
                
                ///保存到本地
                localSave.set(self.userDataDic, forKey: "loginStatus")
                localSave.synchronize()
            }
            
            self.comfun!(_nickName!,_openID!,_openSID!,_headURL!,self.userDataDic)
            
        }) { (session, error) in
            print("\((#file as NSString).lastPathComponent):(\(#line))",session?.getUser() as Any)
            
            print("\((#file as NSString).lastPathComponent):(\(#line))",error?.localizedDescription as Any)
        }

    }
    
}
